package com.fingard.dsp.bank.directbank.yeepay02;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.text.StringHelper;
import com.yeepay.g3.sdk.yop.client.YopRequest;
import com.yeepay.g3.sdk.yop.client.YopResponse;
import com.yeepay.g3.sdk.yop.client.YopRsaClient;
import com.yeepay.g3.sdk.yop.error.YopError;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class YEEPAY02SinglePay extends YEEPAY02Base implements ISinglePay {
    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req1908.singleDetail.payAct, "");
            if (actItem == null) {
                retDetail.respCode = "-1";
                if (actItem == null) {
                    retDetail.respInfo = "未找到账号" + p_req1908.singleDetail.payAct + "的商户配置节点";
                }
                retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                retDetail.transState = PaymentState.FAIL_Payment;
                retDetail.payInfoCode = FailCode.E9981;
                retAts.writeRetDetail(retDetail);
                return retAts;
            }

            Map<String, String> params = new HashMap<String, String>();
            params.put("appKey", actItem.appKey);
            Date date = Format.DateTime14Format.parse(p_req1908.singleDetail.payDate + p_req1908.singleDetail.payTime);
            Calendar ts = Calendar.getInstance();
            ts.setTime(date);
            String transTime = String.valueOf(ts.getTimeInMillis());
            params.put("ts", transTime);
            /*String orderId = p_req1908.singleDetail.askNumber;
            String postScript = p_req1908.singleDetail.abstractATS;
            String localFilePath = createTempFileDirectory() + File.separator + orderId + ".txt";
            WriteBankLogLn2("本地批次流水映射文件路径:" + localFilePath);
            FileHelper.writeFile(localFilePath, postScript, getCharset());*/
            params.put("batchNo", p_req1908.singleDetail.askNumber);
            params.put("orderId", p_req1908.singleDetail.askNumber);
            params.put("amount", p_req1908.singleDetail.payAmount);
            params.put("accountName", p_req1908.singleDetail.recName);
            params.put("accountNumber", p_req1908.singleDetail.recAct);
            params.put("bankCode", convertBankToBank(p_req1908.singleDetail.recBankCode));
            params.put("bankName", p_req1908.singleDetail.recBankName);
            params.put("bankBranchName", p_req1908.singleDetail.recBankLocation);
            String[] areaCode = convertAreaToBank2(p_req1908.singleDetail.recArea);
            params.put("provinceCode", areaCode[0]);
            params.put("cityCode", areaCode[1]);
            params.put("abstractInfo", "");
            String product = getBankConfig().getValueAsString("product");
            if (StringHelper.hasAnyChar(product)) {
                params.put("product", product);
            } else {
                retDetail.respCode = "0";
                retDetail.respInfo = "保险业务类型代码为空,请检查'config/portfiles/YEEPAY02/config.xml'中'product'配置节点信息!";
                retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                retDetail.transState = PaymentState.FAIL_Batch;
                retDetail.payInfoCode = FailCode.E9981;
                retAts.writeRetDetail(retDetail);
                return retAts;
            }
            params.put("feeType", "SOURCE");
            params.put("urgency", p_req1908.singleDetail.paySpd);
            params.put("desc", p_req1908.singleDetail.description);
            params.put("leaveWord", p_req1908.singleDetail.memo);

            String url = bankFront.getUrl("singlePay");
            WriteBankLogLn("提交银行的地址后缀：" + url);
            YopRequest yoprequest = getYoprequest(params, actItem);
            WriteBankLogStep2(yoprequest.toQueryString());

            //向YOP发请求
            YopResponse tmpresponse = YopRsaClient.post(url, yoprequest);
            WriteBankLogStep3(tmpresponse.toString());
            if (tmpresponse != null) {
                String status = tmpresponse.getState();
                Map map = parseResponse(tmpresponse.getStringResult());
                YopError error = tmpresponse.getError();
                if ("SUCCESS".equals(status)) {
                    String errorCode = map.get("errorCode").toString();
                    if ("BAC001".equals(errorCode)) {
                        retDetail.respCode = "0";
                        retDetail.respInfo = "提交成功";
                        retDetail.payInfoCode = errorCode;
                        retDetail.transState = errorCode;
                    } else {
                        retDetail.respCode = "0";
                        retDetail.respInfo = map.get("errorMsg").toString();
                        retDetail.payInfoCode = errorCode;
                        retDetail.transState = errorCode;
                    }
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = error.getSubMessage();
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpresponse.toString();
            }
        } catch (Exception e) {
            retDetail.respCode = "-1";
            retDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }
        retAts.writeRetDetail(retDetail);
        return retAts;
    }

    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        retDetail.reqSeqID = p_req1944.askNumber;
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req1944.payAct, "");
            if (actItem == null) {
                retDetail.respCode = "-1";
                if (actItem == null) {
                    retDetail.respInfo = "未找到账号" + p_req1944.payAct + "的商户配置节点";
                }
                retDetail.reqSeqID = p_req1944.askNumber;
                retDetail.transState = PaymentState.FAIL_Payment;
                retDetail.payInfoCode = FailCode.E9981;
                retAts.writeRetDetail(retDetail);
                return retAts;
            }

            Map<String, String> params = new HashMap<String, String>();
            params.put("appKey", actItem.appKey);
            Date date = Format.DateTime14Format.parse(p_req1944.bgnDate);
            Calendar ts = Calendar.getInstance();
            ts.setTime(date);
            String transTime = String.valueOf(ts.getTimeInMillis());
            params.put("ts", transTime);
            /*String orderId = p_req1944.askNumber;
            String localFilePath = getTempFileDirectory() + File.separator + orderId + ".txt";
            String postScript = FileHelper.readFileText(localFilePath, getCharset());
            WriteBankLogLn2("本地批次流水映射文件内容:\r\n" + postScript);*/
            params.put("batchNo", p_req1944.askNumber);
            params.put("orderId", p_req1944.askNumber);
            String product = getBankConfig().getValueAsString("product");
            if (StringHelper.hasAnyChar(product)) {
                params.put("product", product);
            } else {
                retDetail.respCode = "0";
                retDetail.respInfo = "保险业务类型代码为空,请检查'config/portfiles/YEEPAY02/config.xml'中'product'配置节点信息!";
                retDetail.reqSeqID = p_req1944.askNumber;
                retDetail.transState = PaymentState.FAIL_Batch;
                retDetail.payInfoCode = FailCode.E9981;
                retAts.writeRetDetail(retDetail);
                return retAts;
            }
            params.put("pageNo", "1");
            params.put("pageSize", "100");

            String url = bankFront.getUrl("query");
            WriteBankLogLn("提交银行的地址后缀：" + url);
            YopRequest yoprequest = getYoprequest(params, actItem);
            WriteBankLogStep2(yoprequest.toQueryString());

            //向YOP发请求
            YopResponse tmpresponse = YopRsaClient.post(url, yoprequest);
            WriteBankLogStep3(tmpresponse.toString());
            if (tmpresponse != null) {
                String status = tmpresponse.getState();
                Map map = parseResponse(tmpresponse.getStringResult());
                YopError error = tmpresponse.getError();
                if ("SUCCESS".equals(status)) {
                    String errorCode = map.get("errorCode").toString();
                    if ("BAC001".equals(errorCode)) {
                        retDetail.respCode = "0";
                        retDetail.respInfo = "";
                        JSONArray respList = JSON.parseArray(map.get("list").toString());
                        JSONObject tmpRespJson = respList.getJSONObject(0);
                        retDetail.transAmt = tmpRespJson.getString("amount");
                        String transferStatusCode = tmpRespJson.getString("transferStatusCode");
                        String bankTrxStatusCode = tmpRespJson.getString("bankTrxStatusCode");
                        retDetail.payInfoCode = errorCode + "+" + transferStatusCode + "+" + bankTrxStatusCode;
                        retDetail.transState = errorCode + "+" + transferStatusCode + "+" + bankTrxStatusCode;
                    } else {
                        retDetail.respCode = "0";
                        retDetail.respInfo = map.get("errorMsg").toString();
                        retDetail.payInfoCode = errorCode;
                        retDetail.transState = errorCode;
                    }
                } else {
                    retDetail.respCode = "-1";
                    retDetail.payInfoCode = map.get("code").toString();
                    retDetail.respInfo = error.getSubMessage();
                    retDetail.transState = status;
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpresponse.toString();
            }

        } catch (Exception e) {
            retDetail.respCode = "-1";
            retDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }
        retAts.writeRetDetail(retDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
